package org.example.fastproject.core.utils;

import org.example.fastproject.core.bean.TreeNode;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 王海舟
 * @Date 2023/1/31 11:41
 * @PackageName:org.example.fastproject.core.utils
 * @ClassName: TreeUtil
 * @Description: 树结构工具类
 * @Version 1.0
 */
public class TreeUtil{
    public static <T extends TreeNode> List<T> toTree(List<T> list){
        //根据父id分组
        Map<Long, List<TreeNode>> map = list.stream().collect(Collectors.groupingBy(TreeNode::getParentId));
        //获取根结点列表
        List<TreeNode> roots = map.get(0L);
        //递归生成树
        for(TreeNode root : roots){
            setChildren(root,map);
        }
        //返回根节点列表
        return (List<T>) roots;
    }

    private static void setChildren(TreeNode node, Map<Long, List<TreeNode>> map) {
        Long id = node.getId();
        if(map.containsKey(id)){
            //存在子节点
            List<TreeNode> children = map.get(id);
            node.setChildren(children);
            for(TreeNode child : children){
                setChildren(child,map);
            }
        }
    }
}
